@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

REM 设置颜色
set "RED=[91m"
set "GREEN=[92m"
set "YELLOW=[93m"
set "BLUE=[94m"
set "NC=[0m"

REM 获取版本号
set "VERSION=%1"
if "%VERSION%"=="" (
    echo %RED%错误: 请指定版本号%NC%
    echo %YELLOW%使用方法: remote-deploy.bat [版本号] [服务器地址]%NC%
    echo %YELLOW%示例: remote-deploy.bat v1.0.0 root@192.168.1.100:/opt/deploy%NC%
    pause
    exit /b 1
)

REM 服务器配置
set "SERVER_CONFIG=%2"
if "%SERVER_CONFIG%"=="" (
    set "SERVER_USER=root"
    set "SERVER_HOST=your-server.com"
    set "SERVER_PATH=/opt/likeadmin-python"
) else (
    for /f "tokens=1,2 delims=@" %%a in ("%SERVER_CONFIG%") do (
        set "SERVER_USER=%%a"
        set "SERVER_HOST_PATH=%%b"
    )
    for /f "tokens=1,2 delims=:" %%a in ("%SERVER_HOST_PATH%") do (
        set "SERVER_HOST=%%a"
        set "SERVER_PATH=%%b"
    )
)

echo %GREEN%=== LikeAdmin Python 远程部署脚本 ===%NC%
echo %BLUE%版本号: %VERSION%%NC%
echo %BLUE%服务器: %SERVER_USER%@%SERVER_HOST%:%SERVER_PATH%%NC%

REM 检查SSH是否可用
ssh -V >nul 2>&1
if errorlevel 1 (
    echo %RED%错误: SSH 不可用，请安装 Git Bash 或 WSL%NC%
    pause
    exit /b 1
)

REM 检查服务器连接
echo %YELLOW%检查服务器连接...%NC%
ssh "%SERVER_USER%@%SERVER_HOST%" "echo '连接成功'" >nul 2>&1
if errorlevel 1 (
    echo %RED%错误: 无法连接到服务器%NC%
    echo %YELLOW%请检查网络连接和服务器配置%NC%
    pause
    exit /b 1
)

echo %GREEN%服务器连接正常%NC%

REM 检查文件是否存在
echo %YELLOW%检查部署文件...%NC%
ssh "%SERVER_USER%@%SERVER_HOST%" "test -f %SERVER_PATH%/likeadmin-python-%VERSION%.zip"
if errorlevel 1 (
    echo %RED%错误: 镜像压缩包不存在%NC%
    echo %YELLOW%请先运行 build-and-upload.bat 上传文件%NC%
    pause
    exit /b 1
)

echo %GREEN%部署文件检查通过%NC%

REM 确认部署
echo %YELLOW%确认在服务器 %SERVER_HOST% 上部署版本 %VERSION%？(Y/N)%NC%
set /p "CONFIRM="
if /i not "%CONFIRM%"=="Y" (
    echo %YELLOW%部署已取消%NC%
    pause
    exit /b 1
)

REM 开始远程部署
echo %GREEN%=== 开始远程部署 ===%NC%

REM 配置Docker镜像源
echo %YELLOW%配置Docker镜像源...%NC%
ssh "%SERVER_USER%@%SERVER_HOST%" "sudo cp %SERVER_PATH%/daemon.json /etc/docker/daemon.json && sudo systemctl restart docker"

REM 执行部署脚本
echo %YELLOW%执行部署脚本...%NC%
ssh "%SERVER_USER%@%SERVER_HOST%" "cd %SERVER_PATH% && chmod +x deploy-from-archive.sh && ./deploy-from-archive.sh %VERSION%"

if errorlevel 1 (
    echo %RED%远程部署失败%NC%
    echo %YELLOW%请手动登录服务器检查错误%NC%
    pause
    exit /b 1
)

echo %GREEN%=== 远程部署成功 ===%NC%
echo %BLUE%版本: %VERSION%%NC%
echo %BLUE%服务器: %SERVER_USER%@%SERVER_HOST%:%SERVER_PATH%%NC%

REM 显示服务状态
echo %YELLOW%=== 服务状态 ===%NC%
ssh "%SERVER_USER%@%SERVER_HOST%" "cd %SERVER_PATH% && docker-compose ps"

pause 